package com.edward.puff.repository.impl;

import com.edward.puff.repository.PuffTransLog;
import com.edward.puff.repository.TransLogRepository;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.List;

/**
 * @Author: Edward
 * @Date: 2019/11/28 上午12:06
 */
public class TransLogDefaultRepository implements TransLogRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    private static String INSERT_SQL = "insert into puff_trans_log(tx_log_id,signature,cur_params) values (?,?,?)";

    private static String SELECT_SQL = "select * from puff_trans_log where tx_log_id = ?";

    private static String SELECT_LIST_SQL = "select * from puff_trans_log limit ?";

    private static String DELETE_SQL = "delete from puff_trans_log where id = ?";

    private static String UPDATE_SQL = "update puff_trans_log set retry_count = ?,next_retry_time=? where id = ?";


    /**
     * 保存事务日志
     *
     * @param txLog
     */
    @Override
    public void saveTransLog(PuffTransLog txLog) {
        int ret = jdbcTemplate.update(INSERT_SQL, txLog.getTxLogId(), txLog.getSignature(), txLog.getCurParams());
        if (ret != 1) {
            throw new RuntimeException("txLog insert db fail");
        }
    }

    /**
     * 根据txLogId,查询事务日志
     *
     * @param txLogId
     * @return
     */
    @Override
    public PuffTransLog getTransLog(String txLogId) {
        return jdbcTemplate.queryForObject(SELECT_SQL, BeanPropertyRowMapper.newInstance(PuffTransLog.class), txLogId);
    }

    /**
     * 查询重试TxLog
     *
     * @param count
     * @return
     */
    @Override
    public List<PuffTransLog> queryRetryTranLogs(int count) {
        return jdbcTemplate.query(SELECT_LIST_SQL, BeanPropertyRowMapper.newInstance(PuffTransLog.class), count);
    }

    /**
     * 完结TxLog
     *
     * @param txLogId
     * @return
     */
    @Override
    public boolean finishTransLog(String txLogId) {
        //查询
        PuffTransLog transLog = getTransLog(txLogId);
        if (transLog == null) {
            return true;
        }
        //删除
        jdbcTemplate.update(DELETE_SQL, transLog.getId());
        return true;
    }

    /**
     * 更新PuffTransLog
     *
     * @param txLogId
     * @return
     */
    @Override
    public boolean updateTransLog(String txLogId) {
        //查询
        PuffTransLog transLog = getTransLog(txLogId);
        if (transLog == null) {
            return true;
        }
        //更新重试时间
        jdbcTemplate.update(UPDATE_SQL, transLog.getRetryCount() + 1, LocalTime.now(), transLog.getId());
        return true;
    }
}